package com.apache.passport.controller;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.passport.entity.BlackRoster;
import com.apache.passport.entity.OutwardSys;
import com.apache.passport.entity.SynInfo;
import com.apache.passport.manager.BlackRosterManager;
import com.apache.passport.manager.OutwardSysManager;
import com.apache.passport.manager.SynInfoManager;
import com.apache.tools.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;

//import org.owasp.esapi.ESAPI;

/**
 * description:
 *
 * @author dyh 创建时间：2018年01月29日
 */
@Controller
public class WelcomeAction {

    @Autowired
    private OutwardSysManager outwardSysManager;

    @Autowired
    private SynInfoManager synInfoManager;

    @Autowired
    private BlackRosterManager blackRosterManager;

    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request) {
        String go = request.getParameter("go");
        String cset = request.getParameter("cset");
        String sys = request.getParameter("sys");
        String _client = request.getParameter("_client");
        ModelAndView model = new ModelAndView("login");
        model.addObject("parameter_go", go);
        model.addObject("parameter_cset", cset);
        model.addObject("parameter_sys", sys);
        model.addObject("parameter_client", _client);
        model.addObject("ctx", request.getContextPath());
        //request.getSession().setAttribute("ctx", request.getContextPath());
        return model;
    }

    @RequestMapping(value={"/login.jsp","/passport/login.jsp","/login.html"}, method = RequestMethod.GET)
    public String gotoLogin(HttpServletRequest request, Map<String, Object> data) {
        /*String go = ESAPI.encoder().encodeForHTML(request.getParameter("go"));
        String cset = ESAPI.encoder().encodeForHTML(request.getParameter("cset"));
        String sys = ESAPI.encoder().encodeForHTML(request.getParameter("sys"));
        String _client = ESAPI.encoder().encodeForHTML(request.getParameter("_client"));*/
        String go = request.getParameter("go");
        String cset = request.getParameter("cset");
        String sys = request.getParameter("sys");
        String _client = request.getParameter("_client");
        data.put("parameter_go", go);
        data.put("parameter_cset", cset);
        data.put("parameter_sys", sys);
        data.put("parameter_client", _client);
        data.put("ctx", request.getContextPath());
        request.getSession().setAttribute("ctx", request.getContextPath());
        return "login";
    }

    @RequestMapping(value={"/login_jwt.jsp","/passport/login_jwt.jsp","/login_jwt.html"}, method = RequestMethod.GET)
    public String gotoJwtLogin(HttpServletRequest request, Map<String, Object> data) {
        /*String go = ESAPI.encoder().encodeForHTML(request.getParameter("go"));
        String cset = ESAPI.encoder().encodeForHTML(request.getParameter("cset"));
        String sys = ESAPI.encoder().encodeForHTML(request.getParameter("sys"));
        String _client = ESAPI.encoder().encodeForHTML(request.getParameter("_client"));
        String clientid = ESAPI.encoder().encodeForHTML(request.getParameter("clientid"));
        String redirectUri = ESAPI.encoder().encodeForHTML(request.getParameter("redirect_uri"));
        String responseType = ESAPI.encoder().encodeForHTML(request.getParameter("response_type"));
        String scope = ESAPI.encoder().encodeForHTML(request.getParameter("scope"));*/
        String go = request.getParameter("go");
        String cset = request.getParameter("cset");
        String sys = request.getParameter("sys");
        String _client = request.getParameter("_client");
        String clientid = request.getParameter("clientid");
        String redirectUri = request.getParameter("redirect_uri");
        String responseType = request.getParameter("response_type");
        String scope = request.getParameter("scope");
        data.put("parameter_go", go);
        data.put("parameter_cset", cset);
        data.put("parameter_sys", sys);
        data.put("parameter_client", _client);
        data.put("parameter_clientId", clientid);
        data.put("parameter_redirect_uri", redirectUri);
        data.put("parameter_response_type", responseType);
        data.put("parameter_scope", _client);
        data.put("ctx", request.getContextPath());
        request.getSession().setAttribute("ctx", request.getContextPath());
        return "login";
    }

    /**
     * 跳到控制台页面
     */
    @RequestMapping(value = "/passport/ssosys/console", method = RequestMethod.GET)
    public String console(HttpServletRequest request, HttpServletResponse response,
            Map<String, Object> data) throws ServletException, IOException {
        data.put("title", "统一登录系统管理控制台");
        data.put("ctx", request.getContextPath());
        return "/passport/passport-console";
    }

    /**
     * 外部系统管理
     */
    @RequestMapping(value = "/passport/ssosys/sys-list", method = RequestMethod.GET)
    public String sysList(HttpServletRequest request, HttpServletResponse response,
            Map<String, Object> data) throws ServletException, IOException {
        data.put("title", "统一登录系统管理控制台");
        data.put("ctx", request.getContextPath());
        return "/passport/passport-sys-list";
    }

    /**
     * 外部系统管理，进入增加页面
     */
    @RequestMapping(value = "/passport/ssosys/sys-save", method = RequestMethod.GET)
    public String sysSave(HttpServletRequest request, HttpServletResponse response,
            Map<String, Object> data) throws ServletException, IOException {
        data.put("title", "统一登录系统管理控制台");
        data.put("ctx", request.getContextPath());
        String sysId = request.getParameter("sysId");
        if (Validator.isNotNull(sysId)) {
            ParamsVo vo = new ParamsVo();
            vo.setInfoId(sysId);
            OutwardSys item = (OutwardSys) outwardSysManager.getInfoById(vo);
            data.put("item", item);
            vo.setParams("sysEname", item.getSysEname());
            vo.setMethodKey("sysEnameQuery");
            ResultEntity result = (ResultEntity) synInfoManager.execute(vo);
            SynInfo synInfo = new SynInfo();
            if (!"F".equals(result.getEntity())) {
                synInfo = (SynInfo) result.getEntity();
            }
            data.put("item2", synInfo);
            data.put("isAdd", "false");
        } else {
            data.put("item", new OutwardSys());
            data.put("item2", new SynInfo());
            data.put("isAdd", "");
        }
        return "/passport/passport-sys-save";
    }

    /**
     * 黑名单管理
     */
    @RequestMapping(value = "/passport/black/black-list", method = RequestMethod.GET)
    public String blackList(HttpServletRequest request, HttpServletResponse response,
            Map<String, Object> data) throws ServletException, IOException {
        data.put("title", "统一登录系统管理控制台");
        data.put("ctx", request.getContextPath());
        return "/passport/passport-black-list";
    }

    /**
     * 黑名单管理，进入增加页面
     */
    @RequestMapping(value = "/passport/black/black-save", method = RequestMethod.GET)
    public String blackSave(HttpServletRequest request, HttpServletResponse response,
            Map<String, Object> data) throws ServletException, IOException {
        data.put("title", "统一登录系统管理控制台");
        data.put("ctx", request.getContextPath());
        String sysId = request.getParameter("sysId");
        if (Validator.isNotNull(sysId)) {
            ParamsVo vo = new ParamsVo();
            vo.setInfoId(sysId);
            data.put("item", blackRosterManager.getInfoById(vo));
            data.put("isAdd", "false");
        } else {
            data.put("item", new BlackRoster());
            data.put("isAdd", "");
        }
        return "/passport/passport-black-save";
    }

    /**
     * 受限制用户管理
     */
    @RequestMapping(value = "/passport/cache/cache-list", method = RequestMethod.GET)
    public String cacheList(HttpServletRequest request, HttpServletResponse response,
            Map<String, Object> data) throws ServletException, IOException {
        data.put("title", "统一登录系统管理控制台");
        data.put("ctx", request.getContextPath());
        return "/passport/passport-cache-list";
    }

    /**
     * 当前登录用户列表
     */
    @RequestMapping(value = "/passport/cache/cache-user-list", method = RequestMethod.GET)
    public String cacheUserList(HttpServletRequest request, HttpServletResponse response,
            Map<String, Object> data) throws ServletException, IOException {
        data.put("title", "统一登录系统管理控制台");
        data.put("ctx", request.getContextPath());
        return "/passport/passport-cache-user-list";
    }

    /**
     * 登录登出历史列表
     */
    @RequestMapping(value = "/logger/sign/sign-list", method = RequestMethod.GET)
    public String signList(HttpServletRequest request, HttpServletResponse response,
            Map<String, Object> data) throws ServletException, IOException {
        data.put("title", "统一登录系统管理控制台");
        data.put("ctx", request.getContextPath());
        return "/passport/sys-list";
    }

    /**
     * 跳到错误页面
     */
    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String error(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        data.put("errors", "对不起,您没有访问权限");
        return "/error/error";
    }

    /**
     * 跳到license错误页面
     */
    @RequestMapping(value="/errorPage", method = RequestMethod.GET)
    public String toPage(HttpServletRequest request, Map<String, Object> data) {
        String error = request.getParameter("Errorcode");
        String[] params = new String[0];
        if ("errorCode-00000001".equals(error)) {
            error = getMessage(request, "invalid-001", params, "");
        } else if ("errorCode-00000002".equals(error)) {
            error = getMessage(request, "invalid-002", params, "");
        } else {
            error = getMessage(request, "invalid-003", params, "");
        }
        data.put("ctx", request.getContextPath());
        data.put("Errorcode", error);
        return "/error/invalid";
    }

    /**
     * 获取国际化信息
     *
     * @param msgKey key message_*.properties文件中的key
     * @param params key中{0}、{1}等对应的值
     * @param defaultMessage 对应的默认值
     * @return 返回对应的国际化信息
     */
    private String getMessage(HttpServletRequest request, String msgKey, String[] params,
                              String defaultMessage) {
        WebApplicationContext requestContext = RequestContextUtils.findWebApplicationContext(request);
        Locale myLocale = RequestContextUtils.getLocale(request);
        String msg = requestContext.getMessage(msgKey, params, defaultMessage, myLocale);
        return StrUtil.doNull(msg, defaultMessage);
    }
}
